package knowse.app.parser;

import java.io.IOException;
import java.util.ArrayList;

import knowse.app.FetchData;
import knowse.app.daos.ProjectDAO;
import knowse.app.daos.TestStatusDAO;
import knowse.app.daos.TestStatusDataObject;
import knowse.app.daos.TestStatusDetailDAO;
import knowse.app.daos.TestStatusDetailDataObject;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.util.Log;

public class Parser {
	
	private final String TAG = "Parser";
	private final String hostUrl ="http://cse-212240.cse.chalmers.se/feldt/courses/agile2012/data/knowse/";
	private final String contentsFileUrl= hostUrl + "contents.txt";
	String knowsePrefix ="knowse";
	FetchData fd;
	private String test;
	
	private String test1;
	
	public Parser(){
		fd = new FetchData();
		fetchContentsFile();
	}
	
	private void fetchContentsFile(){
		try{
			String contentsFileString = fd.fetchData(contentsFileUrl);
			
			String[] contents = contentsFileString.split("\n");
			String[] filenames = new String[contents.length];
			
			for(int i = 0; i < contents.length; i++){
				String tmp = contents[i];
				String tmp2 = tmp.substring(0, tmp.indexOf(","));
				if(tmp2.startsWith(knowsePrefix)){
					filenames[i] = tmp2;
				}
			}
			
			//fetch and parse projects
			ProjectDAO p = new ProjectDAO();
			p.store();
			
			//fetch the knowse_ruby_test.csv
			String knowse_ruby_test_csv_url = hostUrl + filenames[1];
			String knowse_ruby_test_csv_String = (String)fd.fetchCSV(knowse_ruby_test_csv_url);			
			//parse knowse_ruby_test.csv
			parseKnowSERubyTest(knowse_ruby_test_csv_String);

			//For each ruby_test.json
				//Fetch
				//Parse
			for(int i = 3; i < filenames.length; i++){
				JSONArray jArr = fd.fetchJSON(hostUrl+filenames[i]);
				for(int j = 0; j < jArr.length(); j++){
					try {
						JSONObject jObj = jArr.getJSONObject(j);
						parseKnowSETestProblem(jObj,filenames[i]);
					} catch (JSONException e) {
						Log.e(TAG, e.getMessage());
					}
				}
			}
		}catch(IOException e){
			Log.e(TAG, e.getMessage());
		}
	}
	
	public void parseKnowSERubyTest(String rubyTestFile){
		try{
			TestStatusDAO t = new TestStatusDAO();
			String[] rubyTestLine = rubyTestFile.split("\n");
			for(int i = 1; i < rubyTestLine.length; i++){
				TestStatusDataObject tdo = new TestStatusDataObject(rubyTestLine[i]);
				t.store(tdo);
			}
		}catch(Exception e){
			Log.d(TAG, e.getMessage());
		}

	}
	
	public void parseKnowSETestProblem(JSONObject jObj, String filename){
		try {
			TestStatusDetailDataObject tdo = new TestStatusDetailDataObject(jObj, filename);
			TestStatusDetailDAO tdao = new TestStatusDetailDAO();
			tdao.store(tdo);
		}catch (JSONException e) {
			Log.e(TAG, e.getMessage());
		}catch(Exception e){
			Log.e(TAG, e.getMessage());
		}
	}
	
	
}
